package com.docking.heylo.web.interceptor;

import com.docking.heylo.ThreadContext;
import com.docking.heylo.pojo.Request;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Component
public class GlobalizationInterceptor implements HandlerInterceptor {

    /****
     * 设置语言环境
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");

        Request req = new Request();
        
        // 设置访问者IP
        req.setIp(getIp(request));
        ThreadContext.authorize.set(req);
        return true;
    }

    /***
     * 离开 & 移除
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadContext.authorize.remove();
    }


    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");

        //多次反向代理后会有多个ip值，第一个ip才是真实ip
        if(isIp(ip)){
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }

        ip = request.getHeader("X-Real-IP");
        if(isIp(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }

    public static boolean isIp(String ip){
        return !StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip);
    }










}
